package com.example.mobiledatapackage.config;

import com.example.mobiledatapackage.exception.RuleFileCannotFoundError;
import org.apache.jena.reasoner.Reasoner;
import org.apache.jena.reasoner.rulesys.GenericRuleReasoner;
import org.apache.jena.reasoner.rulesys.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Configuration
public class ReasonerBean {

    @Bean
    public Reasoner getReasoner() throws RuleFileCannotFoundError {
        // 获取规则文件
        Reasoner reasoner;
        var resource = new ClassPathResource("\\rule\\recommendRule-dev.rules");
        try (
                BufferedReader ruleFileReader = new BufferedReader(new InputStreamReader(resource.getInputStream()))
        ) {
            // 解析规则文件并获得推理机
            reasoner = new GenericRuleReasoner(Rule.parseRules(Rule.rulesParserFromReader(ruleFileReader)));
        } catch (IOException e) {
            throw new RuleFileCannotFoundError();
        }
        return reasoner;
    }
}
